import { ref } from 'vue'

const useCountLoop = () => {
  const disabled = ref(false)
  const btnText = ref('获取验证码')
  const countdown = ref()
  // 手机验证码的倒计时
  const doLoop = (seconds = 60) => {
    if (countdown.value) {
      return true
    }
    disabled.value = true
    btnText.value = '重新获取(' + seconds + 's)'
    countdown.value = setInterval(() => {
      if (seconds > 0) {
        --seconds
        if (seconds < 10) {
          seconds = '0' + seconds
        }
        btnText.value = '重新获取(' + seconds + 's)'
      } else {
        btnText.value = '重新获取'
        disabled.value = false
        clearInterval(countdown.value)
        countdown.value = null
      }
    }, 1000)
    return false
  }

  const clearLoop = () => {
    if (countdown.value) {
      clearInterval(countdown.value)
      countdown.value = null
      btnText.value = '获取验证码'
    }
  }
  return {
    doLoop,
    clearLoop,
    btnText,
    disabled,
  }
}

export default useCountLoop
